package com.bachelor.community.service.impl;

import com.bachelor.community.mapper.TagMapper;
import com.bachelor.community.model.entity.Tag;
import com.bachelor.community.service.intf.TagService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    @Resource
    private TagMapper tagMapper;

    @Override
    public List<Tag> findTagsByQuestionId(Long questionId) {
        return null;
    }

    @Override
    public List<Tag> insertTags(List<String> tagNames) {
        List<Tag> tags = new ArrayList<>();
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        tagNames.forEach(tagName -> {
            queryWrapper.eq("name", tagName);
            Tag tag = getOne(queryWrapper, true);
            if (tag == null) {
                tag = Tag.builder().name(tagName).build();
                save(tag);
            } else {
                tag.setCount(tag.getCount() + 1);
                updateById(tag);
            }
            tags.add(tag);
        });
        return tags;
    }

    @Override
    public List<String> selectTagsName() {
        List<Tag> tags = list();
        return tags.stream().map(Tag::getName).collect(Collectors.toList());
    }

    @Override
    public List<Tag> searchTags(String keyword) {
        return tagMapper.listTagsByKeyword(keyword);
    }
}
